﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using PaperSystem.Models;

namespace PaperSystem.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        LoginRepository _loginRepository;
        PublicRepository _pulbicRepository;
        public LoginController()
        {
            _loginRepository = new LoginRepository();
            _pulbicRepository = new PublicRepository();
        }
        //显示登录页面
        public ActionResult Index()
        {
            ViewData["List"] = _loginRepository.CreateDropdownList();
            return View();
        }

        //接收登录页面数据
        [HttpPost]
        public ActionResult Index(LoginInfo info)
        {
            if (_loginRepository.LoginVerify(info))
            {
                //Session["userId"] = info.user;//不使用session，无法实现多用户同时登陆
                //Session["userName"] = _loginRepository.UserName(info);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, info.user, DateTime.Now, DateTime.Now.AddMinutes(240), true, info.role);
                string encTicket = FormsAuthentication.Encrypt(authTicket);//加密
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                cookie.Expires = DateTime.Now.AddMinutes(240);//可持续登录240min
                this.Response.Cookies.Add(cookie);
                if (info.role.Equals("管理员"))
                {
                    return Redirect("/Admin/Management");
                }
                else if (info.role.Equals("教师"))
                {
                    return Redirect("/Question/QuestionList");
                }
                else if (info.role.Equals("学生"))
                {
                    return Redirect("/Paper/ExamPaperList");
                }
            }
            //登录失败返回本页，需要dropdownlist内容
            ViewData["List"] = _loginRepository.CreateDropdownList();
            ViewData["errorMessage"] = "登录失败，请检查用户名和密码";
            return View();
        }

        //退出登录
        public ActionResult Logout()
        {
            //cookies还保留着
            //删除名字为“FormsAuthentication.FormsCookieName”的cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie.Expires = DateTime.Now.AddMinutes(-1);
            this.Response.Cookies.Add(cookie);
            return Redirect("/Login/Index/");
        }
    }
}
